package com.mq.config;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;


/**
 * ClassName: RabbitConfig
 * Package: com.mq.config
 * Description:
 *
 * @Author: @weixueshi
 * @Create: 2024/8/7 - 15:40
 * @Version: v1.0
 */

/**
 * 交换机和队列的确认回调配置
 */
@Slf4j
@Configuration
public class RabbitConfig implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnsCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 将配置挂载到RabbitTemplate上才能生效
     */
    @PostConstruct
    public void initRabbitTemplate() {
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
    }

    /**
     *  消息发送到交换机成功或失败的回调函数
     * @param correlationData correlation data for the callback.
     * @param ack true for ack, false for nack
     * @param cause An optional cause, for nack, when available, otherwise null.
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        log.info("confirm() 回调函数打印correlationData：{}",correlationData);
        log.info("confirm() 回调函数打印ack：{}",ack);
        log.info("confirm() 回调函数打印cause：{}",cause);
    }

    /**
     * 消息发送到队列失败的回调函数
     * @param returnedMessage the returned message and metadata.
     */
    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {
        log.info("消息主体：{}", new String(returnedMessage.getMessage().getBody()));
        log.info("应答码：{}",returnedMessage.getReplyCode());
        log.info("描述：{}",returnedMessage.getReplyText());
        log.info("消息使用的交换机 exchange：{}",returnedMessage.getExchange());
        log.info("消息使用的路由键 routing：{}",returnedMessage.getRoutingKey());
    }
}
